using System;
using System.Collections.Generic;
using System.Text;
using GameFramework;
using GameEngine;

namespace Projet_X0
{
    public class Ennemy : Character
    {
        public Ennemy(Vector2D position, float direction, int characterID, Player player, float health, Weapons weapons)
            : base(position, direction, characterID, new IAControl(), health, weapons)
        {
            if (weapons != null)
                weapons.AddWeapon(new Weapon(500, 3, 10, 1000, 1000));
            control.Set(this, player);
        }

        public class IAControl : Action
        {
            public IAControl(Ennemy source, Entity target)
                : base(source, target)
            {
            }

            public IAControl()
                : base()
            {
            }

            public override void Run()
            {
                Ennemy ennemy = (Ennemy)source;
                Position sourcePos = ennemy.position;
                Orientation orientation = ennemy.orientation;
                Position destPos = (Position)target.GetState((int)StatesID.Position);
                float oldAngle = orientation.Get();
                float angle = (float)Math.PI / 2 + (float)Math.Atan2(destPos.GetPos().GetY() - sourcePos.GetPos().GetY(), destPos.GetPos().GetX() - sourcePos.GetPos().GetX());
                angle -= oldAngle;

                if (Math.Sin(angle) > 0)
                {
                    ennemy.rotateLeft.Activate(false);
                    ennemy.rotateRight.Activate(true);
                    ennemy.moveFront.Activate(true);
                }
                else
                    if (Math.Sin(angle) < 0)
                    {
                        ennemy.rotateLeft.Activate(true);
                        ennemy.rotateRight.Activate(false);
                        ennemy.moveFront.Activate(true);
                    }
                    else
                    {
                        ennemy.moveFront.Activate(true);
                        ennemy.rotateLeft.Activate(false);
                        ennemy.rotateRight.Activate(false);
                    }
                float portee = 0f;
                if (ennemy.weapons != null)
                {
                    portee = ennemy.weapons.GetWeapon().GetPortee();

                    if (Math.Abs(Math.Sin(angle)) < 0.1 && Math.Atan2(Math.Abs(sourcePos.GetPos().GetY() - destPos.GetPos().GetY()), Math.Abs(sourcePos.GetPos().GetX() - destPos.GetPos().GetX())) < portee)
                    {
                        ennemy.fire.Activate(true);
                    }
                    else
                    {
                        ennemy.fire.Activate(false);
                    }
                }

            }
        }
    }
}
